<template>
  <el-dialog
    top="30px"
    width="800px"
    title="放款通知书"
    append-to-body
    :close-on-click-modal="false"
    :before-close="beforeClose"
    :visible.sync="visible"
  >
    <div v-loading="loading">
      <div class="text-right mb-2">
        <el-button @click="getData()" icon="el-icon-refresh" :loading="loading">刷新</el-button>
        <el-button @click="handleView" :disabled="!letter.doc_id">查看放款通知书</el-button>
      </div>
      <table class="table table-bordered table-vertical-middle text-center" v-loading="loading">
        <tr>
          <td width="18%" class="td-label">客户名称</td>
          <td width="32%">{{ related.customer_name }}</td>
          <td width="18%" class="td-label">证件号</td>
          <td width="32%" :class="tdClass">
            {{ +related.customer_type === 1 ? related.register_no : related.lender_idcard }}
          </td>
        </tr>
        <tr>
          <td class="td-label">放款银行</td>
          <td :class="tdClass">
            <span v-if="isView">{{ letter.bank_name }}</span>
            <el-input v-else v-model="letter.bank_name" placeholder="放款银行"></el-input>
          </td>
          <td class="td-label">放款金额</td>
          <td :class="tdClass">
            <span v-if="isView">{{ letter.apply_funds }} 万元</span>
            <el-input
              v-else
              placeholder="放款金额"
              v-model="letter.apply_funds"
              v-input-number="{ min: 0, fixed: 2 }"
              @change="setCapital"
            >
              <span slot="append">万元</span>
            </el-input>
          </td>
        </tr>
        <tr>
          <td class="td-label">保证合同号</td>
          <td :class="tdClass">
            <span v-if="isView">{{ letter.ensure_contract_no }}</span>
            <el-input
              v-else
              v-model="letter.ensure_contract_no"
              placeholder="保证合同号"
            ></el-input>
          </td>
          <td :class="tdClass">
            <span v-if="isView">{{ letter.loan_contract_name }}</span>
            <c-select
              v-else
              :options="[{ label: '借款合同' }, { label: '授信合同' }]"
              :props="{ value: 'label', label: 'label' }"
              v-model="letter.loan_contract_name"
            ></c-select>
          </td>
          <td :class="tdClass">
            <span v-if="isView">{{ letter.loan_contract_no }}</span>
            <el-input v-else v-model="letter.loan_contract_no" placeholder="借款合同号"></el-input>
          </td>
        </tr>
        <tr>
          <td class="td-label">贷款期限</td>
          <td :class="tdClass">
            <span v-if="isView">{{ letter.load_years }} 月</span>
            <el-input
              v-else
              v-model="letter.load_years"
              v-input-number="{ min: 0, fixed: 0 }"
              placeholder="贷款期限"
            >
              <span slot="append">月</span>
            </el-input>
          </td>
          <td class="td-label">委托合同号</td>
          <td :class="tdClass">
            <span v-if="isView">{{ letter.entrust_gua_no }}</span>
            <el-input
              v-else
              type="textarea"
              v-model="letter.entrust_gua_no"
              placeholder="委托合同号"
            ></el-input>
          </td>
        </tr>
      </table>
      <div class="text-center py-4" v-if="!isView">
        <el-button
          type="primary"
          class="btn-long"
          :loading="submitLoading"
          @click="submit(0)"
          :disabled="+letter.sign_status === 2"
        >
          保存
        </el-button>
        <el-button
          type="primary"
          class="btn-long"
          :loading="submitLoading"
          @click="submit(1)"
          :disabled="+letter.sign_status > 0"
        >
          盖章
        </el-button>
      </div>

      <div class="text-center py-4" v-if="!viewMode && +letter.sign_status > 0">
        <el-button type="primary" class="btn-long" :loading="submitLoading" @click="reRecord">
          重开放款通知书
        </el-button>
      </div>

      <el-dialog
        top="30px"
        width="900px"
        append-to-body
        :close-on-click-modal="false"
        :before-close="CloseView"
        :visible.sync="letterView"
      >
        <pdf-view :contract-id="contractId" :view-mode="true"></pdf-view>
      </el-dialog>
    </div>
  </el-dialog>
</template>

<script>
import { nzhToMoney } from '@vimi/utils-tool'
import { mapGetters } from 'vuex'
import PdfView from '@/credit/views/county/unionProvince/components/PdfView'
export default {
  components: {
    PdfView,
  },
  props: {
    visible: Boolean,
    viewMode: {
      type: Boolean,
      default: false,
    },
    queryId: String,
    related: {
      type: Object,
      default: () => {},
    },
  },
  data() {
    return {
      inputOptions: {
        min: 0,
        max: 100,
        fixed: 2,
        onMin: () => this.$message.error('不能小于0'),
        onMax: () => this.$message.error('不能超过100'),
        onFixed: () => this.$message.error('小数点不能超过2位数'),
      },
      loading: false,
      tableName: 'loan_notice',
      letter: {},
      letterView: false,
      submitLoading: false,
      contractId: '',
    }
  },

  created() {},
  computed: {
    ...mapGetters(['org', 'clientId', 'user']),
    isView() {
      return this.viewMode || +this.letter.sign_status > 0
    },
    tdClass() {
      return this.isView ? '' : 'input-td'
    },
    letterId() {
      return this.letter.loan_notice_id
    },
  },
  watch: {
    queryId: {
      handler: function () {
        this.getData()
      },
      immediate: true,
    },
  },
  methods: {
    setCapital() {
      this.letter.apply_funds_capital = nzhToMoney(+this.letter.apply_funds * 10000)
    },
    reRecord() {
      this.$prompt('请输入重开理由', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputValidator: value => (!value ? '请输入重做原因' : true),
      })
        .then(({ value }) => {
          this.submitLoading = true
          this.$api
            .addData('credit', 're_sign_record', {
              sign_no: this.letter.sign_no,
              doc_id: this.letter.doc_id,
              related_id: this.letterId,
              sign_no_type: 5,
              re_sign_des: value,
              re_sign_person: this.user.realName,
              re_sign_time: this.$utils.dateFormat(new Date()),
              customer_related_id: this.queryId,
              is_re_sign_dir: 1,
            })
            .then(() => {
              this.getData()
              this.$message.success('提交成功！')
              this.handleSuccess()
            })
            .catch(() => this.$message.error(`操作失败，请重试！`))
            .finally(() => {
              this.submitLoading = false
            })
        })
        .catch(() => {})
    },

    validator() {
      const tipMessage = {
        bank_name: '请输入放款银行名称',
        apply_funds: '请输入放款金额',
        ensure_contract_no: '请输入保证合同号',
        loan_contract_no: '请输入借款合同号',
        load_years: '请输入贷款期限',
        entrust_gua_no: '请输入委托合同号',
      }
      for (let key of Object.keys(tipMessage)) {
        if (!this.letter[key]) {
          return tipMessage[key]
        }
      }
      return ''
    },
    submit(type) {
      const inputErr = this.validator()
      if (inputErr) {
        return this.$message.warning(inputErr)
      }
      this.submitLoading = true
      this.sendLetter(type)
        .then(() => {
          this.getData()
          this.$message.success('保存成功！')
          this.handleSuccess()
        })
        .catch(err => {
          this.$message.error(err?.data?.error_description || `操作失败，请重试！`)
        })
        .finally(() => {
          this.submitLoading = false
        })
    },
    sendLetter(type) {
      const data = {
        customer_related_id: this.queryId,
        apply_funds_capital: nzhToMoney(+this.letter.apply_funds * 10000),
        apply_funds: this.letter.apply_funds,
        ensure_contract_name: '保证合同',
        ensure_contract_no: this.letter.ensure_contract_no,
        loan_contract_name: this.letter.loan_contract_name,
        loan_contract_no: this.letter.loan_contract_no,
        entrust_gua_no: this.letter.entrust_gua_no,
        load_years: this.letter.load_years,
        bank_name: this.letter.bank_name,

        sign_status: type,
        sign_date: this.$utils.dateFormat(new Date(), 'yyyy年MM月dd日'),
      }
      if (!this.letterId) {
        return this.$api.addData(this.$serviceName, this.tableName, data)
      } else {
        return this.$api.updateData(this.$serviceName, this.tableName, this.letterId, data)
      }
    },
    CloseView() {
      this.letterView = false
      this.contractId = ''
    },
    handleView() {
      this.contractId = this.letter.doc_id
      this.letterView = true
    },
    getData() {
      if (!this.queryId) {
        return
      }
      this.loading = true
      Promise.all([
        this.$api.getData(this.$serviceName, 'entrust_contract', {
          'customer_related_id.eq': this.queryId,
        }),
        this.$api.getData(
          this.$serviceName,
          this.tableName,
          {
            'customer_related_id.eq': this.queryId,
          },
          { create_time: 'desc' }
        ),
      ])
        .then(([entrust, letter]) => {
          this.entrustContract = entrust?.data?.[0] ?? {}
          this.letter = letter?.data?.[0] ?? {
            apply_funds_capital: this.entrustContract.reply_funds_capital,
            apply_funds:
              this.entrustContract.reply_funds ||
              +this.related.approved_funds ||
              this.related.apply_funds,
            ensure_contract_no: this.entrustContract.ensure_contract_no,
            loan_contract_no: this.entrustContract.loan_contract_no,
            entrust_gua_no: this.entrustContract.entrust_contract_cno,
            load_years: this.entrustContract.load_years || +this.related.months || '',
            bank_name: this.entrustContract.bank_name || this.related.bank_name,
            loan_contract_name: '借款合同',
          }
          this.$emit('getDocId', this.letter?.doc_id)
        })
        .catch(() => {
          this.submitLoading = true
        })
        .finally(() => {
          this.loading = false
        })
    },
    beforeClose() {
      this.$emit('update:visible', false)
    },
    handleSuccess() {
      this.$emit('success', true)
    },
  },
}
</script>
<style lang="scss" scoped></style>
